﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Imaging;

namespace 远程监控客户端
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            while (true)
            {
                TcpClient tcp = new TcpClient();

                IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("10.16.13.58"), 12561);
                try
                {
                    tcp.Connect(endPoint);
                }
                catch (Exception)
                {
                    await Task.Delay(1000);
                    continue;
                }

                while (true)
                {
                    try
                    {
                        List<byte> data = new List<byte>();

                        byte[] buffer = CaptureScreen();
                        int length = buffer.Length;
                        byte[] header = BitConverter.GetBytes(length);
                        data.AddRange(header);
                        data.AddRange(buffer);
                        NetworkStream ns = tcp.GetStream();

                        await ns.WriteAsync(data.ToArray(), 0, data.Count);

                        //await ns.ReadAsync(buffer, 0, buffer.Length);
                    }
                    catch (Exception)
                    {

                        break;
                    }
                   
                }
            }
        

        }

        public static byte[] CaptureScreen()
        {
            // 创建一个新的位图，大小与屏幕相同
            Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);

            // 从位图创建一个图形对象
            Graphics graphics = Graphics.FromImage(bitmap);

            // 捕捉整个屏幕
            graphics.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);

            // 保存截图
            using (MemoryStream ms = new MemoryStream())
            {
                bitmap.Save(ms, ImageFormat.Jpeg);
                return ms.ToArray();
            }
        }
    }
}
